package com.zhangxiaofanfan.hotcode.second;

/**
 * <a href="https://leetcode.cn/problems/merge-k-sorted-lists/description/?envType=study-plan-v2&envId=top-100-liked">合并 K 个升序链表</a>
 *
 * @author zhangxiaofanfan
 * @date 2024-05-29 08:42:05
 */
public class HotCode034 {
    public static void main(String[] args) {
        ListNode list1 = new ListNode(1);
        list1.next = new ListNode(4);
        list1.next.next = new ListNode(5);
        ListNode list2 = new ListNode(1);
        list2.next = new ListNode(3);
        list2.next.next = new ListNode(6);
        ListNode list3 = new ListNode(2);
        list3.next = new ListNode(6);
        HotCode034 hotCode = new HotCode034();
        hotCode.mergeKLists(new ListNode[]{list1, list2, list3});
    }

    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return new ListNode();
        }
        ListNode head = new ListNode();
        ListNode index = head;
        while (true) {
            int minValueIndex = -1;
            for (int i = 0; i < lists.length; i++) {
                if (lists[i] == null) {
                    continue;
                }
                if (minValueIndex == -1 || lists[i].val < lists[minValueIndex].val) {
                    minValueIndex = i;
                }
            }
            if (minValueIndex == -1) {
                index.next = null;
                return head.next;
            } else {
                index.next = lists[minValueIndex];
                lists[minValueIndex] = lists[minValueIndex].next;
                index = index.next;
            }
        }
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
